package api;

import com.fasterxml.jackson.databind.ObjectMapper;
import model.Guser;
import model.Puser;
import model.Ruser;


import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

@WebServlet("/api/current-user.json")
public class UserApi extends HttpServlet {

    private final ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        HttpSession session = req.getSession();
        Puser currentUser1 = (Puser) session.getAttribute("pcurrentUser");
        Ruser currentUser2 = (Ruser) session.getAttribute("rcurrentUser");
        Guser currentUser3 = (Guser) session.getAttribute("gcurrentUser");
        Object result = null;

        if(currentUser1 == null||currentUser2==null||currentUser3==null) {
            result = new Object() {
                public boolean logged = false;
            };
        } if(currentUser1!=null){
            result = new Object(){
                public Integer logged = 1;
                public Puser user = currentUser1;
            };
        }if(currentUser2!=null){
            result = new Object(){
                public Integer logged = 2;
                public Ruser user = currentUser2;
            };
        }if(currentUser3!=null){
            result = new Object(){
                public Integer logged = 3;
                public Guser user = currentUser3;
            };
        }

        String json = objectMapper.writerWithDefaultPrettyPrinter().writeValueAsString(result);
        resp.setContentType("application/json");
        resp.setCharacterEncoding("utf-8");
        resp.getWriter().println(json);
    }
}
